package com.uy.cuantoconocesdeuruguay.dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.uy.cuantoconocesdeuruguay.R;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.utiles.ApplicationUtils;

public class ErrorOccurredDialogUtils {
	private Activity activity;	
	private Exception exception;
	public ErrorOccurredDialogUtils(Activity activity, Exception exception) {
		this.activity = activity;
		this.exception = exception;
	}

	public void createErrorOccurredPopup(){
		Runnable mainThreadRunnable = new Runnable() {			
			@Override
			public void run() {	
				if (activity == null || activity.isFinishing()){
					return;
				}
				GoogleAnalyticsTracker.trackException(activity, exception);
				View view = activity.getLayoutInflater().inflate(R.layout.error_occurred_dialog, null);		
				
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			    builder.setView(view);
			    builder.setCancelable(false);
			    final Dialog errorOccurredPopup = builder.create();
				errorOccurredPopup.show();	
				errorOccurredPopup.setOnKeyListener(new Dialog.OnKeyListener() {
		            @Override
		            public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
		                if (keyCode == KeyEvent.KEYCODE_BACK) {
		                    ApplicationUtils.pressHomeButton(activity);
		                    errorOccurredPopup.dismiss();
		                }
		                return true;
		            }
		        });
		
				Button accept = (Button)view.findViewById(R.id.error_accept);
				accept.setOnClickListener(new OnClickListener() {			
					@Override
					public void onClick(View v) {
						ApplicationUtils.restartApplication(activity);
					}
				});
			}
		};
		activity.runOnUiThread(mainThreadRunnable);
	}
}
